<template>
  <div class="page-container user-list-container">
    <div class="page-title">
      用户管理
    </div>
    
    <!-- 搜索和操作栏 -->
    <div class="search-area">
      <div class="search-input-wrapper">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入用户名搜索"
          class="search-input"
          clearable
          @clear="handleSearch"
          :prefix-icon="Search"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <el-button type="primary" @click="openAddUserDialog" class="add-button">
        <el-icon><Plus /></el-icon> 添加用户
      </el-button>
    </div>
    
    <!-- 用户列表 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
        :stripe="true"
        :highlight-current-row="true"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.role === 'admin' ? 'danger' : 'success'"
              effect="plain"
              size="large"
              class="role-tag"
            >
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" v-if="userList.length > 0 && userList[0].createTime" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <div class="button-group">
              <el-button 
                size="small" 
                type="primary" 
                plain
                @click="handleEdit(scope.row)"
              >
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                plain
                @click="handleDelete(scope.row)"
                :disabled="scope.row.id === currentUser.id || scope.row.username === 'admin'"
                :title="getDeleteButtonTitle(scope.row)"
              >
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            :disabled="isEdit && !resetPassword"
            show-password
          />
          <div v-if="isEdit" class="form-tip">
            <el-checkbox v-model="resetPassword">重置密码</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select 
            v-model="userForm.role" 
            placeholder="请选择角色"
            :disabled="isEditAdminSelf || isEditAdminUser"
            style="width: 100%"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
          <div v-if="isEditAdminSelf" class="form-tip">
            <el-icon><InfoFilled /></el-icon> 管理员不能修改自己的角色
          </div>
          <div v-else-if="isEditAdminUser" class="form-tip">
            <el-icon><InfoFilled /></el-icon> admin用户必须保持管理员角色
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, InfoFilled } from '@element-plus/icons-vue'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser 
} from '@/api/user'
import { useUserStore } from '@/store/user'

// 用户存储
const userStore = useUserStore()
// 获取当前登录用户信息
const currentUser = computed(() => userStore.userInfo || {})

// 列表数据和分页
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const searchKeyword = ref('')

// 添加/编辑表单
const dialogVisible = ref(false)
const isEdit = ref(false)
const resetPassword = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  password: '',
  role: 'user'
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 判断是否为编辑当前登录的管理员自己
const isEditAdminSelf = computed(() => {
  return isEdit.value && 
         userForm.id === currentUser.value.id && 
         currentUser.value.role === 'admin';
});

// 判断是否为编辑admin用户
const isEditAdminUser = computed(() => {
  return isEdit.value && userForm.username === 'admin';
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    const res = await getUserList(params)
    console.log('用户列表API响应:', res.data)
    
    // 数据结构修正：使用records字段作为列表数据
    const records = res.data.records || []
    userList.value = records
    
    // 如果total为0但有记录，则使用记录长度作为total
    total.value = res.data.total > 0 ? res.data.total : records.length
    
    console.log('获取到的用户列表:', userList.value)
    console.log('总数:', total.value)
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 分页和搜索处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 打开添加用户对话框
const openAddUserDialog = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  resetForm()
  isEdit.value = true
  resetPassword.value = false
  
  // 填充数据
  userForm.id = row.id
  userForm.username = row.username
  userForm.role = row.role
  userForm.password = '' // 不回显密码
  
  dialogVisible.value = true
}

// 获取删除按钮提示文字
const getDeleteButtonTitle = (row) => {
  if (row.id === currentUser.value.id) {
    return '不能删除自己的账户'
  }
  if (row.username === 'admin') {
    return '管理员账户不允许删除'
  }
  return '删除用户'
}

// 删除用户
const handleDelete = (row) => {
  // 不能删除自己
  if (row.id === currentUser.value.id) {
    ElMessage.warning('不能删除自己的账户')
    return
  }
  
  // 不能删除admin账户
  if (row.username === 'admin') {
    ElMessage.warning('管理员账户不允许删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log('删除用户ID:', row.id)
      const res = await deleteUser(row.id)
      console.log('删除用户响应:', res)
      
      ElMessage.success('删除用户成功')
      // 重新获取用户列表
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败', error)
      ElMessage.error('删除用户失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
    console.log('用户取消删除操作')
  })
}

// 重置表单
const resetForm = () => {
  userForm.id = ''
  userForm.username = ''
  userForm.password = ''
  userForm.role = 'user'
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 防止admin自己降级权限
      if (isEdit.value && 
          userForm.id === currentUser.value.id && 
          currentUser.value.role === 'admin' && 
          userForm.role !== 'admin') {
        ElMessage.warning('管理员不能将自己的角色降级')
        return
      }
      
      // 防止修改用户名为admin的用户的角色
      if (isEdit.value && 
          userForm.username === 'admin' && 
          userForm.role !== 'admin') {
        ElMessage.warning('不能修改admin用户的角色')
        return
      }
      
      // 编辑模式下，如果不重置密码，则移除密码字段
      const submitData = { ...userForm }
      if (isEdit.value && !resetPassword.value) {
        delete submitData.password
      }
      
      console.log('提交数据:', submitData)
      
      if (isEdit.value) {
        await updateUser(userForm.id, submitData)
        ElMessage.success('更新用户成功')
      } else {
        await createUser(submitData)
        ElMessage.success('添加用户成功')
      }
      
      dialogVisible.value = false
      fetchUserList()
    } catch (error) {
      console.error('操作失败', error)
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-list-container {
  min-height: calc(100vh - 130px);
}

.search-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input-wrapper {
  flex: 1;
  max-width: 400px;
}

.search-input {
  width: 100%;
}

.add-button {
  margin-left: 20px;
}

.role-tag {
  width: 90px;
  text-align: center;
  display: inline-flex;
  justify-content: center;
}

.user-form {
  margin: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media screen and (max-width: 768px) {
  .search-area {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input-wrapper {
    width: 100%;
    max-width: none;
    margin-bottom: 15px;
  }
  
  .add-button {
    margin-left: 0;
    width: 100%;
  }
}
</style> 